<?php
namespace app\controller\crm;

use app\BaseController;
use app\model\crm\LawsuitOrder;
use app\model\crm\LegalServiceOrder;
use app\model\crm\Order;
use app\validate\crm\LawsuitOrderValidate;
use app\validate\crm\LegalServiceOrderValidate;
use think\facade\Db;
use think\facade\Log;
use think\response\Json;

/**
 * 诉讼和法务订单控制器
 * @package app\controller\crm
 */
class LawsuitLegalOrderController extends BaseController
{
    /**
     * 获取诉讼订单列表
     * @return Json
     */
    public function lawsuitOrderList(): Json
    {
        try {
            $page = $this->request->param('page', 1, 'intval');
            $limit = $this->request->param('limit', 10, 'intval');
            $keyword = $this->request->param('keyword', '');
            $status = $this->request->param('status', '');
            
            $query = LawsuitOrder::with(['order', 'customer']);
            
            if ($keyword) {
                $query->whereLike('entrusting_party_name|opposing_party_name|contact_person', "%{$keyword}%")
                      ->whereOr('case_type', 'like', "%{$keyword}%");
            }
            
            if ($status !== '') {
                $query->whereHas('order', function($q) use ($status) {
                    $q->where('status', $status);
                });
            }
            
            $total = $query->count();
            $list = $query->page($page, $limit)
                         ->order('id', 'desc')
                         ->select();
            
            return $this->success([
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            Log::error('获取诉讼订单列表失败: ' . $e->getMessage());
            return $this->error('获取列表失败', 400);
        }
    }
    
    /**
     * 获取诉讼订单详情
     * @param int $id
     * @return Json
     */
    public function lawsuitOrderDetail(int $id): Json
    {
        try {
            $order = LawsuitOrder::with(['order', 'customer'])->find($id);
            if (!$order) {
                return $this->error('订单不存在', 404);
            }
            
            // 处理逗号分隔的字符串为数组
            $order->case_type = $order->case_type ? explode(',', $order->case_type) : [];
            $order->civil_phase = $order->civil_phase ? explode(',', $order->civil_phase) : [];
            $order->criminal_phase = $order->criminal_phase ? explode(',', $order->criminal_phase) : [];
            $order->lawsuit_request_elements = $order->lawsuit_request_elements ? explode(',', $order->lawsuit_request_elements) : [];
            
            return $this->success($order);
        } catch (\Exception $e) {
            Log::error('获取诉讼订单详情失败: ' . $e->getMessage());
            return $this->error('获取详情失败', 400);
        }
    }
    
    /**
     * 创建或更新诉讼订单
     * @return Json
     */
    public function saveLawsuitOrder(): Json
    {
        $data = $this->request->post();
        
        try {
            $validate = new LawsuitOrderValidate();
            if (!$validate->check($data)) {
                return $this->error($validate->getError(), 422);
            }
            
            Db::startTrans();
            
            // 创建或更新基础订单
            $orderData = [
                'customer_id' => $data['customer_id'],
                'order_type' => $data['order_type'],
                'order_category' => 2, // 诉讼订单
                'title' => $data['title'] ?? '诉讼订单',
                'amount' => $data['service_fee_pre'] + ($data['service_fee_post'] ?? 0),
                'payment_type' => $data['payment_type'] ?? 1,
                'status' => $data['status'] ?? 1,
                'payment_status' => $data['payment_status'] ?? 1,
                'contract_status' => $data['contract_status'] ?? 1,
            ];
            
            if (isset($data['order_id']) && $data['order_id']) {
                $order = Order::find($data['order_id']);
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
                $order->save($orderData);
            } else {
                $orderData['user_id'] = $this->request->userInfo->id ?? 1;
                $order = Order::create($orderData);
                $data['order_id'] = $order->id;
            }
            
            // 处理数组转为逗号分隔字符串
            foreach (['case_type', 'civil_phase', 'criminal_phase', 'lawsuit_request_elements'] as $field) {
                if (isset($data[$field]) && is_array($data[$field])) {
                    $data[$field] = implode(',', $data[$field]);
                }
            }
            
            // 创建或更新诉讼订单详情
            if (isset($data['id']) && $data['id']) {
                $lawsuitOrder = LawsuitOrder::find($data['id']);
                if (!$lawsuitOrder) {
                    throw new \Exception('诉讼订单不存在');
                }
                $lawsuitOrder->save($data);
            } else {
                LawsuitOrder::create($data);
            }
            
            Db::commit();
            return $this->success([], '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('保存诉讼订单失败: ' . $e->getMessage());
            return $this->error('保存失败: ' . $e->getMessage(), 400);
        }
    }
    
    /**
     * 删除诉讼订单
     * @param int $id
     * @return Json
     */
    public function deleteLawsuitOrder(int $id): Json
    {
        try {
            Db::startTrans();
            
            $lawsuitOrder = LawsuitOrder::find($id);
            if (!$lawsuitOrder) {
                return $this->error('订单不存在', 404);
            }
            
            // 删除关联的基础订单
            if ($lawsuitOrder->order_id) {
                Order::destroy($lawsuitOrder->order_id);
            }
            
            // 删除诉讼订单详情
            $lawsuitOrder->delete();
            
            Db::commit();
            return $this->success([], '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('删除诉讼订单失败: ' . $e->getMessage());
            return $this->error('删除失败', 400);
        }
    }
    
    /**
     * 获取法务订单列表
     * @return Json
     */
    public function legalOrderList(): Json
    {
        try {
            $page = $this->request->param('page', 1, 'intval');
            $limit = $this->request->param('limit', 10, 'intval');
            $keyword = $this->request->param('keyword', '');
            $status = $this->request->param('status', '');
            
            $query = LegalServiceOrder::with(['order', 'customer']);
            
            if ($keyword) {
                $query->whereLike('customer_name|contact_person', "%{$keyword}%");
            }
            
            if ($status !== '') {
                $query->whereHas('order', function($q) use ($status) {
                    $q->where('status', $status);
                });
            }
            
            $total = $query->count();
            $list = $query->page($page, $limit)
                         ->order('id', 'desc')
                         ->select();
            
            return $this->success([
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            Log::error('获取法务订单列表失败: ' . $e->getMessage());
            return $this->error('获取列表失败', 400);
        }
    }
    
    /**
     * 获取法务订单详情
     * @param int $id
     * @return Json
     */
    public function legalOrderDetail(int $id): Json
    {
        try {
            $order = LegalServiceOrder::with(['order', 'customer'])->find($id);
            if (!$order) {
                return $this->error('订单不存在', 404);
            }
            
            // 处理逗号分隔的字符串为数组
            $order->special_service_types = $order->special_service_types ? explode(',', $order->special_service_types) : [];
            
            return $this->success($order);
        } catch (\Exception $e) {
            Log::error('获取法务订单详情失败: ' . $e->getMessage());
            return $this->error('获取详情失败', 400);
        }
    }
    
    /**
     * 创建或更新法务订单
     * @return Json
     */
    public function saveLegalOrder(): Json
    {
        $data = $this->request->post();
        
        try {
            $validate = new LegalServiceOrderValidate();
            if (!$validate->check($data)) {
                return $this->error($validate->getError(), 422);
            }
            
            Db::startTrans();
            
            // 创建或更新基础订单
            $orderData = [
                'customer_id' => $data['customer_id'],
                'order_type' => 1, // 服务订单
                'order_category' => 3, // 法务订单
                'title' => $data['title'] ?? '法务服务订单',
                'amount' => $data['service_fee'] ?? 0,
                'payment_type' => $data['payment_type'] ?? 1,
                'status' => $data['status'] ?? 1,
                'payment_status' => $data['payment_status'] ?? 1,
                'contract_status' => $data['contract_status'] ?? 1,
            ];
            
            if (isset($data['order_id']) && $data['order_id']) {
                $order = Order::find($data['order_id']);
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
                $order->save($orderData);
            } else {
                $orderData['user_id'] = $this->request->userInfo->id ?? 1;
                $order = Order::create($orderData);
                $data['order_id'] = $order->id;
            }
            
            // 处理数组转为逗号分隔字符串
            if (isset($data['special_service_types']) && is_array($data['special_service_types'])) {
                $data['special_service_types'] = implode(',', $data['special_service_types']);
            }
            
            // 创建或更新法务订单详情
            if (isset($data['id']) && $data['id']) {
                $legalOrder = LegalServiceOrder::find($data['id']);
                if (!$legalOrder) {
                    throw new \Exception('法务订单不存在');
                }
                $legalOrder->save($data);
            } else {
                LegalServiceOrder::create($data);
            }
            
            Db::commit();
            return $this->success([], '保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('保存法务订单失败: ' . $e->getMessage());
            return $this->error('保存失败: ' . $e->getMessage(), 400);
        }
    }
    
    /**
     * 删除法务订单
     * @param int $id
     * @return Json
     */
    public function deleteLegalOrder(int $id): Json
    {
        try {
            Db::startTrans();
            
            $legalOrder = LegalServiceOrder::find($id);
            if (!$legalOrder) {
                return $this->error('订单不存在', 404);
            }
            
            // 删除关联的基础订单
            if ($legalOrder->order_id) {
                Order::destroy($legalOrder->order_id);
            }
            
            // 删除法务订单详情
            $legalOrder->delete();
            
            Db::commit();
            return $this->success([], '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('删除法务订单失败: ' . $e->getMessage());
            return $this->error('删除失败', 400);
        }
    }
}